<template>
  <h2
    class="mb-3 text-2xl font-bold text-center xl:text-3xl enter-x xl:text-left"
  >
    登录
  </h2>
  <AForm
    ref="formRef"
    class="enter-x"
    :model="formData"
    :rules="rules"
    @keypress.enter="handleLogin"
  >
    <AFormItem name="username" class="enter-x">
      <AInput
        v-model:value="formData.username"
        size="large"
        placeholder="请输入账号"
        class="fix-auto-fill"
      >
        <template #prefix>
          <user-outlined />
        </template>
      </AInput>
    </AFormItem>
    <AFormItem name="password" class="enter-x">
      <AInputPassword
        v-model:value="formData.password"
        size="large"
        visibility-toggle
        placeholder="请输入密码"
      >
        <template #prefix>
          <lock-outlined />
        </template>
      </AInputPassword>
    </AFormItem>
    <AFormItem name="captcha" class="enter-x">
      <AInput
        v-model:value="formData.captcha"
        size="large"
        placeholder="请输入验证码"
        class="fix-auto-fill"
      >
        <template #prefix>
          <safety-certificate-outlined />
        </template>
        <template #addonAfter>
          <img class="captcha-img" :src="captchaImg" @click="setCaptchaImg" />
        </template>
      </AInput>
    </AFormItem>

    <AFormItem class="enter-x">
      <AButton
        type="primary"
        size="large"
        block
        :loading="loading"
        @click="handleLogin"
      >
        登录
      </AButton>
    </AFormItem>
  </AForm>
</template>
<script lang="ts" setup>
import type { FormInstance } from "ant-design-vue/es";
import type { Ref } from "vue";
import { useFormRules, useFormValid } from "./useLogin";
import { getUUID } from "@/utils";
const userStore = useUserStore();

const rules = useFormRules();

const formRef = ref<FormInstance>();
const loading = ref(false);

const formData = reactive({
  username: "",
  password: "",
  captcha: "",
  uuid: "",
});

onMounted(() => {
  setCaptchaImg();
});

const { validForm } = useFormValid(formRef as Ref<FormInstance>);
const router = useRouter();
async function handleLogin() {
  const data = await validForm();
  if (!data) return;
  loading.value = true;
  const result = await userStore.login(formData);
  if (result) {
    router.replace("/");
  } else {
    setCaptchaImg();
  }
  loading.value = false;
}

let captchaImg = $ref("");
function setCaptchaImg() {
  formData.uuid = getUUID();
  captchaImg =
    window.location.origin + "/back/captcha.jpg?uuid=" + formData.uuid;
}
</script>
